package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: UserServiceImpl
 *
 * @AUTHOR: zhang
 * DATE: 2023/11/28
 * DESCRIPTION :
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private UserMapper userMapper;
    @Resource
    private JwtProperties jwtProperties;

    public static final String URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     *
     * @param userLoginDTO 临时登录凭证code
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //生成openId
        //(1)获取一个用于发送请求HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //(2)封装一个用于表示请求信息的对象 GET:HttpGet
        Map<String, String> parameters = new HashMap<>();
        parameters.put("appid", weChatProperties.getAppid());
        parameters.put("secret", weChatProperties.getSecret());
        parameters.put("js_code", userLoginDTO.getCode());
        parameters.put("grant_type", "authorization_code");
        //(3)发送get请求
        String loginResult = HttpClientUtil.doGet(URL, parameters);
        //将字符串格式的JSON转化为JSONobject
        JSONObject jsonObject = JSON.parseObject(loginResult);
        //获取openid
        String openid = jsonObject.getString("openid");
        if (Objects.isNull(openid)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //根据openid查询用户信息，没有则新增
        User user = userMapper.selectUserByOpenid(openid);
        if (user == null) {
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }
        //生成令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //封装返回数据
        UserLoginVO userLoginVO = UserLoginVO.builder().id(user.getId()).openid(openid).token(token).build();

        return userLoginVO;
    }
}
